package com.plsjavaweb.ui.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.plsjavaweb.core.ReportsCore;
import com.plsjavaweb.dao.DAOFactory;
import com.plsjavaweb.dao.mapper.ProjectSeatAllocationMapper;
import com.plsjavaweb.logging.LoggingConstants;
import com.plsjavaweb.pojo.CSReportsPOJO;
import com.plsjavaweb.pojo.ProjectPOJO;
import com.plsjavaweb.ui.controler.modelview.ErrorPage;

import java.io.File;
import java.util.Date;

import jxl.*;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;

/**
 * Servlet implementation class ExportReport
 */
@WebServlet("/ExportPmReport")
public class ExportPmReport extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger log = Logger.getLogger(DAOFactory.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ExportPmReport() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.info(LoggingConstants.entryMessage);
		HttpSession session = request.getSession(true);
		if (session.getAttribute("user") == null) {
			log.info(LoggingConstants.sessionExpired);
			ErrorPage errorPage = new ErrorPage();
			errorPage.setErrorTitle("Error Page");
			errorPage.setErrorHeader("Invalid Session");
			errorPage
					.setErrorContent("Session has expired. Please Log-in to start new session");
			errorPage.setReturnUrl("/pls-java-web/Login");
			errorPage.setReturnUrlTitle("Go Back to Login Page");
			request.setAttribute("error", errorPage);
			RequestDispatcher rd = request
					.getRequestDispatcher("error-page.jsp");
			rd.forward(request, response);
		} else {
			String role = (String) session.getAttribute("role");
			if (!role.equalsIgnoreCase("MANAGER")) {
				response.sendRedirect("Home");
				return;
			}
			if (session.getAttribute("projects") == null) {
				response.sendRedirect("Home");
				return;
			}
			List<ProjectPOJO> projects = (List<ProjectPOJO>) session
					.getAttribute("projects");
			ServletOutputStream outputStream = response.getOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
			WritableSheet sheet = workbook.createSheet("PM Report", 0);
			request.setAttribute("projects", projects);
			String managerUsername = (String) session.getAttribute("user");
			String trimedUsername = managerUsername.substring(0,
					managerUsername.indexOf('@'));
			try {
				log.info(LoggingConstants.tryMessage);
				WritableFont times16font = new WritableFont(WritableFont.TIMES,
						16, WritableFont.BOLD, false);
				WritableCellFormat times16format = new WritableCellFormat(
						times16font);
				Label title = new Label(0, 0, trimedUsername + "'s Projects",
						times16format);
				sheet.addCell(title);

				Label projName = new Label(0, 1, "Project Name", times16format);
				sheet.addCell(projName);
				Label totRes = new Label(1, 1, "Total Resource", times16format);
				sheet.addCell(totRes);
				Label totSeat = new Label(2, 1, "Total Seats", times16format);
				sheet.addCell(totSeat);
				Label totAll = new Label(3, 1, "Total Allocated", times16format);
				sheet.addCell(totAll);
				Label totVac = new Label(4, 1, "Total Vacant", times16format);
				sheet.addCell(totVac);
				Label totResev = new Label(5, 1, "Total Reserved",
						times16format);
				sheet.addCell(totResev);

				Label value1 = null;
				Number value2 = null;
				Number value3 = null;
				Number value4 = null;
				Number value5 = null;
				Number value6 = null;
				int count = 2;
				for (ProjectPOJO projectPOJO : projects) {
					value1 = new Label(0, count, projectPOJO.getProjectCode(),
							times16format);
					sheet.addCell(value1);
					value2 = new Number(1, count,
							projectPOJO.getTotalResource(), times16format);
					sheet.addCell(value2);
					value3 = new Number(2, count, projectPOJO.getTotalSeats(),
							times16format);
					sheet.addCell(value3);
					value4 = new Number(3, count, projectPOJO
							.getSeatAllocation().getSeatAllocated(),
							times16format);
					sheet.addCell(value4);
					value5 = new Number(4, count, projectPOJO
							.getSeatAllocation().getSeatVacant(), times16format);
					sheet.addCell(value5);
					value6 = new Number(5, count, projectPOJO
							.getSeatAllocation().getSeatReserved(),
							times16format);
					sheet.addCell(value6);
					count++;
				}

				for (int x = 0; x < 6; x++) {
					CellView cell = sheet.getColumnView(x);
					cell.setAutosize(true);
					sheet.setColumnView(x, cell);
				}

				response.setHeader("Content-disposition",
						"attachment; filename=" + trimedUsername
								+ "_PMReport.xls");
				response.setContentType("application/vnd.ms-excel");
				workbook.write();
				workbook.close();

				response.sendRedirect("PmReports");
			} catch (Exception e) {
				log.info(LoggingConstants.catchMessage);
				log.error(e.getMessage());
			}
		}
	}
}
